<template>
  <div class="app-container">
    <!-- 筛选条件区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="filterParams">
        <el-form-item label="设备类型">
          <el-select v-model="filterParams.deviceType" style="width: 300px;" placeholder="全部设备类型" clearable>
            <el-option v-for="item in deviceTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="安装位置">
          <el-select v-model="filterParams.installationLocation" style="width: 300px;" placeholder="全部位置" clearable>
            <el-option v-for="item in positionOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间范围">
          <el-date-picker v-model="filterParams.dateRange" type="datetimerange" range-separator="至"
            start-placeholder="Start date" end-placeholder="End date" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button type="success" @click="handleExport">导出数据</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 设备数据表格 -->
    <el-card class="mt-1">
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="monitoringDeviceId" label="设备编号" align="center" />
        <el-table-column prop="deviceName" label="设备名称" align="center" />
        <el-table-column prop="deviceType" label="设备类型" align="center" />
        <el-table-column prop="installationLocation" label="安装位置" align="center" />
        <el-table-column prop="realTimeValue" label="实时数据值" align="center">
          <template #default="{ row }">
            {{ row.realTimeValue }}<span style="margin-left: 2px">{{ row.dataUnit }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="dataAccuracy" label="数据精度" align="center">
          <template #default="{ row }">
            ±{{ row.dataAccuracy }}
          </template>
        </el-table-column>
        <el-table-column prop="dataCollectionTime" label="实时时间" align="center" />
        <el-table-column label="操作" aliggn="center" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleViewDetail(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
          :total="pagination.total" layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 详情弹框 -->
    <el-dialog v-model="detailDialogVisible" title="设备详情" width="800px" :close-on-click-modal="false">
      <div class="device-detail-container">
        <!-- 设备基本信息 - 使用Descriptions描述列表 -->
        <div class="device-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="设备编号" align="center">
              {{ currentDevice.monitoringDeviceId }}
            </el-descriptions-item>
            <el-descriptions-item label="设备名称" align="center">
              {{ currentDevice.deviceName }}
            </el-descriptions-item>
            <el-descriptions-item label="设备类型" align="center">
              {{ currentDevice.deviceType }}
            </el-descriptions-item>
            <el-descriptions-item label="安装位置" align="center">
              {{ currentDevice.installationLocation }}
            </el-descriptions-item>
            <el-descriptions-item label="数据源编号" align="center">
              {{ currentDevice.dataSourceId || 'SRC001' }}
            </el-descriptions-item>
            <el-descriptions-item label="传输状态" align="center">
              <el-tag type="success">
                {{ currentDevice.dataVerificationStatus || '正常' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="上次传输时间" align="center">
              {{ currentDevice.dataCollectionTime }}
            </el-descriptions-item>
            <el-descriptions-item label="数据精度" align="center">
              ±{{ currentDevice.dataAccuracy }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 数据图表区域 -->
        <div class="chart-container">
          <div class="chart-header">
            <div class="current-value">
              <span class="label">当前值：</span>
              <span class="value">{{ currentValue }}</span>
              <span class="unit">{{ currentDevice.dataUnit }}</span>
            </div>
            <div class="time-range">
              <el-radio-group v-model="dataType" @change="fetchChartData">
                <el-radio-button :label="1">分钟</el-radio-button>
                <el-radio-button :label="2">小时</el-radio-button>
                <el-radio-button :label="3">天</el-radio-button>
              </el-radio-group>
            </div>
          </div>

          <div class="chart-wrapper">
            <ECharts :option="chartOption" style="width: 100%; height: 300px;" />
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import {
  getDeviceTypeList,
  getInstallPositionList,
  getMonitoringList,
  getDeviceChartData
} from '@/api/prod_operate/data_monitoring'
import ECharts from '@/components/ECharts'

// 筛选参数
const filterParams = ref({
  deviceType: '',
  installationLocation: '',
  dateRange: []
})

// 设备类型下拉选项
const deviceTypeOptions = ref([])
// 安装位置下拉选项
const positionOptions = ref([])

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页参数
const pagination = ref({
  current: 1,
  size: 10,
  total: 2
})

// 详情弹框相关
const detailDialogVisible = ref(false)
const currentDevice = ref({})
const dataType = ref(1) // 1-分钟 2-小时 3-天
const currentValue = ref('74.3')
const chartOption = ref({})

// 获取设备类型下拉列表
const fetchDeviceTypes = async () => {
  try {
    const res = await getDeviceTypeList()
    deviceTypeOptions.value = res.data
  } catch (error) {
    console.error('获取设备类型失败:', error)
  }
}

// 获取安装位置下拉列表
const fetchInstallPositions = async () => {
  try {
    const res = await getInstallPositionList()
    positionOptions.value = res.data
  } catch (error) {
    console.error('获取安装位置失败:', error)
  }
}

// 获取设备列表数据
const fetchMonitoringData = async () => {
  try {
    loading.value = true

    const params = {
      deviceType: filterParams.value.deviceType,
      installationLocation: filterParams.value.installationLocation,
      startTime: filterParams.value.dateRange?.[0] || '',
      endTime: filterParams.value.dateRange?.[1] || '',
      pageNum: pagination.value.current,
      pageSize: pagination.value.size
    }

    const res = await getMonitoringList(params)
    tableData.value = res.rows
    pagination.value.total = res.total
  } catch (error) {
    console.error('获取监测数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取图表数据
const fetchChartData = async () => {
  try {
    const res = await getDeviceChartData({
      id: currentDevice.value.id,
      type: dataType.value
    })

    chartOption.value = {
      tooltip: {
        trigger: 'axis',
      },
      grid: {
        left: '2%',
        right: '2%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: res.data.map(item => item.date),
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          color: '#666'
        }
      },
      yAxis: {
        type: 'value',
        name: currentDevice.value.dataUnit,
        nameTextStyle: {
          color: '#666',
          padding: [0, 30, 0, 0]
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#999'
          }
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
            color: '#eee'
          }
        },
        axisLabel: {
          color: '#666'
        }
      },
      series: [
        {
          name: currentDevice.value.deviceName,
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            color: '#409EFF',
            borderColor: '#fff',
            borderWidth: 2
          },
          lineStyle: {
            width: 3,
            color: '#409EFF'
          },
          data: res.data.map(item => item.value)
        }
      ]
    }
  } catch (error) {
    console.error('获取图表数据失败:', error)
  }
}

// 查询处理
const handleFilter = () => {
  pagination.value.current = 1
  fetchMonitoringData()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.value.size = val
  fetchMonitoringData()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.value.current = val
  fetchMonitoringData()
}

// 导出数据
const handleExport = () => {
  // 这里实现导出逻辑
  console.log('导出数据')
}

// 查看详情
const handleViewDetail = (row) => {
  currentDevice.value = row
  dataType.value = 1
  detailDialogVisible.value = true
  fetchChartData()
}

// 初始化
onMounted(() => {
  fetchDeviceTypes()
  fetchInstallPositions()
  fetchMonitoringData()
})
</script>

<style scoped>
.monitoring-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.device-detail-container {
  padding: 10px;
}

.device-info {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.current-value {
  font-size: 16px;
}

.current-value .value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin: 0 5px;
}


.search-card :deep(.el-form-item),
.search-card :deep(.el-form) {
  margin-bottom: 0px !important;
}
</style>